import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          useMaterial3: false,
          primarySwatch: Colors.blue,
        ),
        home: const MyHome()
    );
  }
}

class MyHome extends StatefulWidget {
  const MyHome({super.key});

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {

  final GlobalKey _globalKey1 = GlobalKey(debugLabel: "1");

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter App"),
      ),
      body:  Center(
        child: Box(key: _globalKey1, color: Colors.red),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //1.可以通过key获取到子widget的state
          var boxState =  _globalKey1.currentState as _BoxState;
          print(boxState._count);

          //2.还可以修改子widget的state
          setState(() {
            boxState._count++;
          });

          //3.调用子widget的方法
          boxState.run();

          //4.获取子widget
          var box =  _globalKey1.currentWidget as Box;
          print(box.color);

          //5.获取子组件的渲染属性
          var renderBox =  _globalKey1.currentContext!.findRenderObject() as RenderBox;
          print(renderBox.size);

        },
        child: const Icon(Icons.refresh),
      ),
    );
  }
}


class Box extends StatefulWidget {

  final Color color;

  const Box({super.key,required this.color});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {

  int _count = 0;

  void run(){
    print("我是box组件的run方法");
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 100,
      height: 100,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(widget.color),
        ),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Text("$_count",style: const TextStyle(fontSize: 30)),
      ),
    );
  }
}

